"""
1.查询数据库数据
2.将数据写入文件中
"""
from pymysql import Connection

from my_package.data_define import ReCord

# -----------1.查询数据库数据--------------
conn = Connection(
    host="localhost",
    port=3306,
    user="root",
    password="root",
    database="py_sql",
    autocommit=True
)
# 获取游标对象
cursor = conn.cursor()
sql = "select * from orders"
cursor.execute(sql)

# 获取查询到的数据
all_data = cursor.fetchall()
data_list: list[ReCord] = []
for data in all_data:
    cord = ReCord(data[0], data[1], data[2], data[3])
    data_list.append(cord)

# 关闭连接
conn.close()

# -------------2.文件写入操作-------------------
txt_file_path = "/Users/dongjian/Documents/学习/python-learn-资料/资料/第13章资料/2011年1~2月销售数据.txt"
json_file_path = "/Users/dongjian/Documents/学习/python-learn-资料/资料/第13章资料/2011年1~2月销售数据JSON.txt"
f1 = open(txt_file_path, "a", encoding="UTF-8")
f2 = open(json_file_path, "a", encoding="UTF-8")
for record in data_list:
    f1.write(f"{record.date},{record.order_id},{record.money},{record.province}\n")
    data_dict = {"date": f"{record.date}", "order_id": f"{record.order_id}", "money": f"{record.money}",
                 "province": f"{record.province}"}
    f2.write(f"{data_dict}\n")

f1.flush()
f1.close()
f2.flush()
f2.close()
